package com.portal.framework.util;

import java.util.Date;
import java.util.Stack;

/**
 * 提供计时功能。 支持嵌套计时，如：
 * 
 * <pre>
 * Timer.getInstance().begin();
 * Timer.getInstance().begin();
 * Timer.getInstance().end(&quot;function2: &quot;);
 * Timer.getInstance().end(&quot;function1: &quot;);
 * </pre>
 * 
 * @author 卢烁波
 * @date 2007-3-10
 */

public class Timer {

	private final static boolean log = true;

	private static Timer instance = null;

	private long beginTime;

	private long endTime;

	private double distance;

	int count = 0;

	private Stack beginTimes = new Stack();

	private Timer() {
	}

	public static Timer getInstance() {
		if (instance == null) {
			instance = new Timer();
		}
		return instance;
	}

	public void begin() {
		beginTime = new Date().getTime();
		beginTimes.push(Long.toString(beginTime));
	}

	public double end() {
		endTime = new Date().getTime();
		if (beginTimes.isEmpty()) {
			return 0;
		}
		beginTime = Long.parseLong((String) beginTimes.pop());
		this.distance = (endTime - beginTime) / 1000.00;
		return distance;
	}

	public void end(String str) {
		this.end();
		if (log) {
			System.out.println(str + this.distance);
		}
	}
}
